<?php


namespace app\api\service;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\admin\model\Account;
use app\lib\exception\MessageException;
use Driver\Cache\Redis;
use think\Exception;
use think\facade\Request;

class AliMessage
{
    private $ali;
    private $sign_name;
    private $template_code;
    private $phone;
    private $code;
    private $momey; // 是否扣费成功

    /**
     * AliMessage constructor.
     * @throws ClientException
     */
    public function __construct()
    {
        $this->ali = config('ali.');
        AlibabaCloud::accessKeyClient($this->ali['accessKeyId'], $this->ali['accessKeySecret'])
            ->regionId($this->ali['message']['regionId'])
            ->asDefaultClient();
        $this->code = rand(1000,9999);
    }

    /**
     * 获取阿里云验证码
     * @return array
     * @throws MessageException
     */
    public function set_message($phone, $account_info, $sign)
    {
        $this->phone = $phone;
        $this->get_template_code_and_name($account_info);
        $result = $this->request_ali_message($phone);
        # 扣费
        if($sign !== null){
            $success = $this->deduction($phone, $account_info, $sign);
        }
        $result['momey'] = $this->momey;
        return $result;
    }

    # 获取短信签名和短信模板id
    private function get_template_code_and_name($account_info)
    {
        $this->sign_name = $account_info['sign_name'];
        $this->template_code = $account_info['template_code'];
    }

    # 调用阿里云api发送短信
    private function request_ali_message()
    {
        try {
            $result = AlibabaCloud::rpc()
                ->product($this->ali['message']['product'])
                ->version($this->ali['message']['version'])
                ->action($this->ali['message']['action'])
                ->method($this->ali['message']['method'])
                ->options([
                    'query' => [
                        'RegionId' => $this->ali['message']['regionId'],
                        'PhoneNumbers' => $this->phone,
                        'SignName' => $this->sign_name,
                        'TemplateCode' => $this->template_code,
                        'TemplateParam' => json_encode(['code'=>$this->code]),
                    ],
                ])
                ->request()->toArray();
            if($result['Code'] == 'OK'){

                Redis::set("PhoneNum_".$this->phone,$this->code,300);
                return [
                    'success' => true,
                    'code' => 200,
                    'type' => 'ali'
                ];
            }else{
                throw new MessageException([
                    'code' => 400,
                    'msg' => $result['Code'],
                    'data' => $result,
                    'errorCode' => 30004
                ]);
            }
        } catch (ClientException $e) {
            throw new MessageException([
                'msg' => $e->getErrorMessage()
            ]);
        } catch (ServerException $e) {
            throw new MessageException([
                'msg' => $e->getErrorMessage()
            ]);
        }
    }
    # 短信扣费
    private function deduction($phone, $account_info, $sign)
    {
        try{
        $ip = Request::ip();
        $company_logo = $account_info['logo'];
        $channel = $sign;
        $operator = $account_info['message_id'];
        $type = 1;
        $url = "http://bams.laimibus.com/c/c/mra.html?phone=$phone&ip=$ip&company_logo=$company_logo&channel=$channel&operator=$operator&type=$type";
        $success = json_decode(get($url), true);
        if($success['code'] == 1){
            $this->momey = true;
        }else{
            $this->momey = false;
        }
        }catch (\Exception $e){
            $this->momey = true;
        }
    }

    public function test_message($phone)
    {
        $this->sign_name = '测试';
        $this->phone = $phone;
        $this->template_code = 'SMS_168827474';
        return $this->request_ali_message();
    }
}